import { emptyUser, useUserStore } from "../store/user";
import { User } from "../type/entity";
import { router } from "../router";

// 当从后端获得正确的user对象时调用此函数
export function startIn(user: User, rememberMe: boolean){
  const userStore = useUserStore()
  localStorage.setItem('rememberMe', String(rememberMe))
  localStorage.setItem('token', user.token || '')
  userStore.user = user
}

// 当想要退出登陆或清除个人信息时调用此函数
export function quitOut(){
  const userStore = useUserStore()
  localStorage.removeItem('rememberMe')
  localStorage.removeItem('token')
  userStore.user = emptyUser
  router.push({name: 'Login'})
}

export function formatTime(timeStick: number){
  let date = new Date(timeStick)
  let dateString = date.getFullYear() + '-' + (date.getMonth() + 1).toString().padStart(2, '0')
     + '-' + date.getDate().toString().padStart(2, '0') + ' '
  let timeString = date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0')
  return dateString + timeString
}


// 作者：李瑞丰_liruifengv
// 链接：https://juejin.cn/post/7186865959628455991
// 来源：稀土掘金
export const copyText = async (val:string) => {
  if (navigator.clipboard && navigator.permissions) {
    await navigator.clipboard.writeText(val)
  } else {
    const textArea = document.createElement('textArea') as HTMLTextAreaElement
    textArea.value = val
    textArea.style.width = '0'
    textArea.style.position = 'fixed'
    textArea.style.left = '-999px'
    textArea.style.top = '10px'
    textArea.setAttribute('readonly', 'readonly')
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
  }
}

